package com.threedt.nova.portfolio.reader;

import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.List;

import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageBuilder;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import com.threedt.nova.portfolio.pojo.NewsItem;
import com.threedt.nova.portfolio.transformer.SyndFeedToNewsItemTransformer;


public class SimpleFeedReader implements Serializable {

	private String feedURL;
	private FeedFetcherCache feedInfoCache;
	private FeedFetcher feedFetcher;
	private SyndFeedToNewsItemTransformer syndFeedToNewsItemTransformer;

	public String getFeedURL() {
		return feedURL;
	}

	public void setFeedURL(String feedURL) {
		this.feedURL = feedURL;
	}

	public SyndFeedToNewsItemTransformer getSyndFeedToNewsItemTransformer() {
		return syndFeedToNewsItemTransformer;
	}

	public void setSyndFeedToNewsItemTransformer(
			SyndFeedToNewsItemTransformer syndFeedToNewsItemTransformer) {
		this.syndFeedToNewsItemTransformer = syndFeedToNewsItemTransformer;
	}

	

	public List<NewsItem> receive() throws Exception{
		System.out.println("readRssFeed method is called");
		
		SyndFeedInput input = new SyndFeedInput();
        SyndFeed feed = input.build(new XmlReader(new URL(feedURL)));
        		
		Message<SyndFeed> syndFeeds = MessageBuilder.withPayload(feed).setHeader("feedid", "gridshore").build();
		if(syndFeeds==null){
			System.out.println("syndFeeds is null ...");
			return null;
		}
		
		return syndFeedToNewsItemTransformer.transformNew(syndFeeds);

	}

/*	private SyndFeed obtainFeedItems() {
		SyndFeed feed = null;
		try {
			feedInfoCache = HashMapFeedInfoCache.getInstance();
			if(feedInfoCache== null){
				System.out.println("feedInfoCache catch is null .....");
			}
			feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
			if(feedFetcher== null){
				System.out.println("feedFetcher catch is null .....");
			}
			
			// "http://www.gridshore.nl/feed/";
			feed = feedFetcher.retrieveFeed(new URL("http://www.gridshore.nl/feed/"));
		} catch (IOException e) {
			System.out.println("IO Problem while retrieving feed" + e);
		} catch (FeedException e) {
			System.out.println("Feed Problem while retrieving feed" + e);
		} catch (FetcherException e) {
			System.out.println("Fetcher Problem while retrieving feed" + e);
		}
		return feed;
	}*/
	
}
